from .base import BaseSelectable, INDICATOR_CHAR
from .socketserver import SocketServer


class SocketSelectable(BaseSelectable):
    """
    A selectable using a socket underneath, so that it works on Windows.
    """
    
    def __init__(self):
        super(SocketSelectable, self).__init__()
        self.read_socket, self.write_socket = SocketServer().get_socket_pair()
        # the sockets should never block, but just in case they do, throw an error
        self.read_socket.setblocking(0)
        self.write_socket.setblocking(0)
        self._is_set = False
    
    def set(self):
        with self._lock:
            if not self._is_set:
                assert(self.write_socket.send(INDICATOR_CHAR) == 1)
                assert(self.wait(0.001))
                self._is_set = True
    
    def is_set(self):
        return self._is_set
    
    def clear(self):
        with self._lock:
            if self._is_set:
                assert(INDICATOR_CHAR == self.read_socket.recv(1))
                assert(not self.wait(0.001))
                self._is_set = False
            
    def fileno(self):
        return self.read_socket.fileno()